package com.quotes.datamodell;

import java.io.File;
import javax.swing.event.EventListenerList;
import org.apache.log4j.Logger;
import com.quotes.Configuration;
import com.quotes.dates.TimePeriod;
import com.quotes.dates.TimeRange;
import com.quotes.dates.TimeRangeFactory;
import com.quotes.io.DerbyAdapter;
import com.quotes.io.ExcelAdapter;
import com.quotes.io.YahooQuotesReader;

public class DataRepository
{
	private Logger logger = Logger.getLogger(getClass().toString());
	private boolean dataLoaded = false;
	private SymbolList symbolList = null;
	private QuotesList quotesList = null;
	protected EventListenerList listenerList = new EventListenerList();
	
	public boolean isDataLoaded() {
		return dataLoaded;
	}
	
	public QuotesList getQuotesList() {
		return quotesList;
	}
	
	public boolean tryLoadFromExcel() {
		logger.debug("Loading quotes from excel!");
		File file = new File(Configuration.getExcelFileName());
		
		if (!file.exists()) {
			logger.debug("Excel-File not existing!");
			return false;
		}
		
		ExcelAdapter excel = new ExcelAdapter(Configuration.getExcelFileName());
		
		if (this.symbolList == null)
			this.symbolList = excel.loadSymbols();

		this.quotesList = excel.loadQuotes(symbolList);
		this.dataLoaded = true;
		this.fireDataChangedEvent();
		return true;
	}
	
	public boolean trySaveToExcel() {
		logger.debug("Saving quotes to excel!");
		
		if (dataLoaded) {
			ExcelAdapter excel = new ExcelAdapter(Configuration.getExcelFileName());
			excel.saveQuotes(this.quotesList);
			return true;
		}

		return false;
	}
	
	public boolean tryLoadFromYahoo() {
		logger.debug("Loading quotes from yahoo!");
		
		try {
			YahooQuotesReader reader = new YahooQuotesReader(this.symbolList);
			TimeRange range = TimeRangeFactory.untilToday(TimePeriod.THREE_YEARS);
			this.quotesList = reader.loadQuotes(range);
			this.dataLoaded = true;
			this.fireDataChangedEvent();
			return true;
		} catch (Exception e) {
			logger.error("Could not load quotes from Yahoo!", e);
			return false;
		}
	}
	
	public boolean tryLoadFromDb() {
		logger.debug("Loading quotes from DB!");
		
		try {
			DerbyAdapter derby = new DerbyAdapter();
			this.symbolList = derby.getSymbols();
			this.quotesList = derby.getQuotes(symbolList);
			this.dataLoaded = true;
			this.fireDataChangedEvent();
			return true;
		} catch (Exception e) {
			logger.error("Could not load quotes from DB!", e);
			return false;
		}
	}
	
	public boolean trySaveToDb() {
		logger.debug("Saving quotes to DB!");
		
		if (!dataLoaded)
			return false;
		
		try {
			DerbyAdapter derby = new DerbyAdapter();
			derby.setSymbols(symbolList);
			derby.setQuotes(quotesList);
			return true;
		} catch (Exception e) {
			logger.error("Could not save quotes to DB!", e);
			return false;
		}
	}
	
    public void addDataChangedEventListener(DataChangedEventListener listener) {
    	logger.debug("Listener to DataChangedEvent added: " + listener.toString());
        listenerList.add(DataChangedEventListener.class, listener);
    }
    
    public void removeDataChangedEventListener(DataChangedEventListener listener) {
        listenerList.remove(DataChangedEventListener.class, listener);
    }
    
    private void fireDataChangedEvent() {
    	logger.debug("DataChanged event raised!");
        Object[] listeners = listenerList.getListenerList();

        for (int i=0; i<listeners.length; i+=2) {
            if (listeners[i] == DataChangedEventListener.class) {
                ((DataChangedEventListener)listeners[i+1]).dataChanged(this);
            }
        }
    }

	public SymbolList getSymbols() {
		return symbolList;
	}
}
